import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'dva'
import {Row, Tabs} from 'antd'
import {Page} from 'components'
import {ChartCard} from 'components/Charts'
import {WxChat} from 'components/WeChat'
import CustomerFriendCircleList from './components/FriendList'
import FundRecordsList from '../../fundRecords/components/List'
import OrderList from '../../orders/components/DetailList'
import AddressList from './components/AddressList'
import Detail from "./components/Detail"
import {findCustomerChatRecords} from '../../personalChatRecords/services/personalChatRecords'

const {TabPane} = Tabs

class CustomerDetail extends React.Component {

  constructor (props) {
    super(props)
    this.state = {
      upperTimes: 0,
      underTimes: 0,
      upperId: 0,
      underId: 6,
      defaultOwnerAvatar: '/public/a/' + (parseInt(Math.random() * 15, 10) + 1) + '.jpg',
      defaultContactAvatar: '/public/a/' + (parseInt(Math.random() * 15, 10) + 1) + '.jpg',
    }
  }

  render () {
    const {
      allOrder,
      customerDetail,
      customerFriendCircle,
      fundRecords,
      dispatch,
      loading,
      location,
    } = this.props
    const {upperTimes, underTimes, upperId, underId, defaultOwnerAvatar, defaultContactAvatar} = this.state

    const {data, disabled, friendType, adAcquireType, list: chatRecordsList, pagination: personalChatRecordsPage, currentAddr, addrModalType, addrModalVisible, addressList, addressPage} = customerDetail
    const {list: orderList, pagination: orderPage} = allOrder
    const {list: fundRecordsList, pagination: fundRecordsPage} = fundRecords
    const {list: customerFriendCircleList, pagination: customerFriendCirclePage} = customerFriendCircle

    const detailProps = {
      data,
      friendType,
      adAcquireType,
      disabled,
      onEdit () {
        dispatch({
          type: 'customerDetail/updateState',
          payload: {
            disabled: false,
          },
        })
      },
      onCancel () {
        dispatch({
          type: 'customerDetail/updateState',
          payload: {
            disabled: true,
          },
        })
      },
      handleUpdate (payload) {
        dispatch({
          type: 'customerDetail/update',
          payload,
        })
      },
    }

    const customerFriendCircleListProps = {
      rowKey: 'id',
      dataSource: customerFriendCircleList,
      loading: loading.effects['customerFriendCircle/query'],
      pagination: customerFriendCirclePage,
      location,
      onChange (page) {
        dispatch({
          type: 'customerFriendCircle/query',
          payload: {
            current: page.current,
            size: page.pageSize,
          },
        })
      },
    }

    const orderListProps = {
      rowKey: 'id',
      dataSource: orderList,
      loading: loading.effects['allOrder/query'],
      orderPage,
      location,
      pagination: orderPage,
      onChange (page) {
        dispatch({
          type: 'allOrder/query',
          payload: {
            current: page.current,
            size: page.pageSize,
          },
        })
      },
    }

    const fundRecordsListProps = {
      rowKey: 'id',
      dataSource: fundRecordsList,
      loading: loading.effects['fundRecords/query'],
      pagination: fundRecordsPage,
      location,
      onChange (page) {
        dispatch({
          type: 'fundRecords/query',
          payload: {
            current: page.current,
            size: page.pageSize,
          },
        })
      },
    }

    const getItem = () => {
      currentAddr.customerId = data.id
      return currentAddr
    }

    const addressListProps = {
      rowKey: 'id',
      modalVisible: addrModalVisible,
      dataSource: addressList,
      loading: loading.effects['customerDetail/queryAddress'],
      pagination: addressPage,
      modalType: addrModalType,
      item: getItem(),
      location,
      dispatch,
    }

    const updateState = payload => {
      this.setState({...payload})
    }

    const weChatProps = {
      ownerAvatarUrl: (data.operatorWxId ? data.operatorWxId.icon : undefined) || defaultOwnerAvatar,
      contactAvatarUrl: data.icon || defaultContactAvatar,
      data: chatRecordsList,
      recommended: chatRecordsList.length > 0 ? chatRecordsList[0].isRecommand : false,
      getUpperData () {
        return new Promise(function (resolve) {
          resolve([])

          updateState({
            upperId: upperId + 2,
            upperTimes: upperTimes + 1,
          })
        })
      },

      getUnderData () {
        //意义同getUpperData()
        return new Promise(function (resolve) {
          findCustomerChatRecords({
            current: Number(personalChatRecordsPage.current) + 1,
            cid: data.id,
            owxId: data.operatorWxId.wxId,
          }).then(res => {
            if (res.code === 0 && res.data.records.length > 0) {
              let newData = res.data.records
              dispatch({
                type: 'customerDetail/updatePagination',
                payload: {
                  current: Number(personalChatRecordsPage.current) + 1,
                },
              })
              resolve(newData)
            } else {
              resolve([])
            }
          })

          updateState({
            underId: underId + 2,
            underTimes: underTimes + 1,
          })
        })
      },
    }

    const handleTabsChange = (activeKey) => {
      const payload = {
        current: 1,
        size: 10,
      }
      let type = ""
      switch (activeKey) {
        case 'personalChatRecords_list':
          break
        case 'allOrder_list':
          type = 'allOrder/query'
          payload.customerWxId = data.id
          payload.wxId = data.operatorWxId.wxId
          break
        case 'fundRecords_list':
          type = 'fundRecords/query'
          payload.friendWxId = data.id
          payload.operatorWxId = data.operatorWxId.wxId
          break
        case 'address_info':
          type = 'customerDetail/queryAddress'
          payload.customerId = data.id
          break
        case 'customerFriendCircle_list':
          type = 'customerFriendCircle/query'
          payload.customerWx = data.id
          payload.operatorWx = data.operatorWxId.wxId
          break
        default:
          break
      }
      if (type) {
        dispatch({type, payload})
      }
    }

    return (
      <div>
        <Row gutter={24}>
          <ChartCard style={{marginBottom: 12}}>
            <Detail {...detailProps} />
          </ChartCard>
        </Row>
        <Row gutter={24}>
          <Page inner>
            <Tabs onChange={handleTabsChange}>
              <TabPane tab={'聊天记录'} key={'personalChatRecords_list'}>
                <WxChat {...weChatProps} />
              </TabPane>
              <TabPane tab={'订单明细'} key={'allOrder_list'}>
                <OrderList {...orderListProps} />
              </TabPane>
              <TabPane tab={'资金明细'} key={'fundRecords_list'}>
                <FundRecordsList {...fundRecordsListProps} />
              </TabPane>
              <TabPane tab={'收货信息'} key={'address_info'}>
                <AddressList {...addressListProps} />
              </TabPane>
              <TabPane tab={'朋友圈明细'} key={'customerFriendCircle_list'}>
                <CustomerFriendCircleList {...customerFriendCircleListProps} />
              </TabPane>
            </Tabs>
          </Page>
        </Row>
      </div>
    )
  }
}

CustomerDetail.propTypes = {
  customerDetail: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
}

export default connect(({customerDetail, customerFriendCircle, fundRecords, allOrder, loading}) => ({
  customerDetail,
  customerFriendCircle,
  fundRecords,
  allOrder,
  loading,
}))(CustomerDetail)
